<template>
  <div class="login-container">
    <div class="login-form-container">
      <div class="login-header">
        <img src="https://img.icons8.com/color/96/000000/heart-health.png" alt="康养中心" class="logo" />
        <h1>康养中心患者监护系统--医生端</h1>
        <p>专业、贴心的康养服务平台</p>
      </div>
      
      <el-form ref="formRef" :model="loginForm" :rules="loginRules" class="login-form">
        <el-form-item prop="username">
          <el-input 
            v-model="loginForm.username" 
            :prefix-icon="User"
            placeholder="请输入用户名/手机号/邮箱">
          </el-input>
        </el-form-item>
        
        <el-form-item prop="password">
          <el-input 
            v-model="loginForm.password" 
            :prefix-icon="Lock"
            type="password" 
            placeholder="请输入密码"
            show-password>
          </el-input>
        </el-form-item>
        
        <div class="login-options">
          <el-checkbox v-model="rememberMe">记住我</el-checkbox>
          <el-link type="primary" underline="never">忘记密码?</el-link>
        </div>
        
        <el-button type="primary" class="login-button" @click="handleLogin" :loading="loading">登录</el-button>
        
        <div class="register-link">
          还没有账号? <el-link type="primary" @click="$router.push('/register')" underline="never">立即注册</el-link>
        </div>
      </el-form>
    </div>
    
    <div class="login-decoration">
      <div class="decoration-overlay">
        <h2>用心呵护，专业守护</h2>
        <p>我们致力于为患者提供全方位的健康管理和监护服务</p>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { User, Lock } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { listDoctors } from '@/api/doctors'
import { useUserStore } from '@/stores/user'

const router = useRouter()
const route = useRoute()
const userStore = useUserStore()

const loginForm = reactive({
  username: '',
  password: ''
})

const loginRules = {
  username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
  password: [{ required: true, message: '请输入密码', trigger: 'blur' }]
}

const loading = ref(false)
const rememberMe = ref(false)
const formRef = ref(null)

const handleLogin = () => {
  formRef.value.validate(async (valid) => {
    if (valid) {
      loading.value = true
      try {
        // 调用listDoctors API查询医生列表
        const response = await listDoctors({
          username: loginForm.username
        })
        
        // 检查响应数据结构
        if (!response || !Array.isArray(response)) {
          throw new Error('服务器响应数据格式错误')
        }
        
        // 检查是否有匹配的医生账号
        const doctors = response
        if (doctors.length > 0) {
          // 确保字段与doctors表一致: id, name, specialty, contact, username, password
          const doctor = doctors.find(doc => doc.password === loginForm.password)
          
          if (doctor) {
            // 登录成功
            try {
              // 只存储用户id到pinia
              userStore.setUserInfo({
                id: doctor.id
              })
              console.log('登录后用户ID:', userStore.id)
              
              // 如果记住我，则保存到localStorage
              if (rememberMe.value) {
                localStorage.setItem('userInfo', JSON.stringify({
                  username: loginForm.username,
                  password: loginForm.password
                }))
              }
              
              ElMessage.success('登录成功')
              
              // 跳转到来源页面或默认页面
              const redirectPath = route.query.redirect || '/dashboard'
              router.push(redirectPath)
            } catch (storageError) {
              console.error('存储用户信息失败:', storageError)
              ElMessage.error('登录过程中出现错误，请重试')
            }
          } else {
            ElMessage.error('密码错误')
          }
        } else {
          ElMessage.error('用户名不存在')
        }
      } catch (error) {
        console.error('登录失败:', error)
        ElMessage.error(error.message || '登录失败，请稍后再试')
      } finally {
        loading.value = false
      }
    }
  })
}
</script>

<style scoped>
.login-container {
  display: flex;
  height: 100vh;
  overflow: hidden;
}

.login-form-container {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  padding: 20px;
  background-color: #fff;
}

.login-header {
  text-align: center;
  margin-bottom: 40px;
}

.login-header h1 {
  font-size: 24px;
  color: #409EFF;
  margin: 16px 0 8px;
}

.login-header p {
  color: #909399;
  font-size: 14px;
}

.logo {
  width: 80px;
  height: 80px;
}

.login-form {
  width: 100%;
  max-width: 360px;
}

.login-options {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.login-button {
  width: 100%;
  height: 44px;
  font-size: 16px;
  margin-bottom: 20px;
}

.register-link {
  text-align: center;
  font-size: 14px;
  color: #606266;
}

.login-decoration {
  flex: 1.2;
  position: relative;
  overflow: hidden;
  display: none;
  background: url('https://images.unsplash.com/photo-1631815588090-d4bfec5b9211?ixlib=rb-4.0.3&auto=format&fit=crop&w=800&q=80') center center no-repeat;
  background-size: cover;
}

@media (min-width: 992px) {
  .login-decoration {
    display: block;
  }
}

.decoration-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: linear-gradient(rgba(0, 0, 0, 0.3), rgba(0, 0, 0, 0.6));
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  color: white;
  padding: 40px;
  text-align: center;
}

.decoration-overlay h2 {
  font-size: 32px;
  margin-bottom: 20px;
  font-weight: 500;
}

.decoration-overlay p {
  font-size: 18px;
  max-width: 400px;
  line-height: 1.6;
}
</style> 